package com.loyal.client;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Looper;

public class LoadingHandler extends Handler {
    private ProgressDialog progressDialog;
    private final Context context;
    private final DialogInterface.OnCancelListener onCancelListener;

    public LoadingHandler(Context context, int theme, DialogInterface.OnCancelListener cancelListener) {
        super(Looper.myLooper());
        this.context = context;
        this.onCancelListener = cancelListener;
        initDialog(theme);
    }

    private void initDialog(int theme) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(context, theme);
            progressDialog.setOnCancelListener(onCancelListener);
        }
    }

    public void setMessage(CharSequence message) {
        if (null != progressDialog)
            progressDialog.setMessage(message);
    }

    public void setCancelable(boolean cancelable) {
        if (null != progressDialog)
            progressDialog.setCancelable(cancelable);
    }

    public void setCanceledOnTouchOutside(boolean flag) {
        if (null != progressDialog)
            progressDialog.setCanceledOnTouchOutside(flag);
    }

    public void dismissDialog() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    public void showDialog() {
        if (context instanceof Activity && ((Activity) context).isFinishing())
            return;
        if (null != progressDialog && !progressDialog.isShowing()) {
            progressDialog.show();
        }
    }
}
